package model;

import database.Database;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import session.Session;
import user.User;

/**
 * LoginPage class extends the base model class in order to implement the login
 * page functionality of the Lithub website.
 *
 * @author Reynaldo Gonzales.
 * @version 1.0
 *
 */
public class LoginPage extends Model {

    public Boolean userLoggedIn;
    public String username;
    public String password;
    public int userID;
    private HttpServletRequest request;

    /**
     * LoginPage() is the reciever of a login page request from a user on the
     * lithub website to be processed.
     *
     * @param a HttpServletRequest request which holds the username and password
     * information of the user who wants to sign in.
     *
     */
    public LoginPage(HttpServletRequest req) {
        userLoggedIn = false; // Default to false
        username = req.getParameter("username");
        password = req.getParameter("password");
        request = req;
    }

    /**
     * invoke() is a validity check type invokation method, which is used when a
     * user wants to sign into the Lithub website.
     *
     * @param action String which needs to correspond to the "login" action in order
     * to sign a user in.
     *
     */
    @Override
    public void invoke(String action) {
        if (action.equals("login")) {
            userLoggedIn = tryLoggingIn(username, password);
        }
    }

    /**
     * tryLoggingIn implements the sign in and start-session fucntionality of
     * the lithub website.
     *
     * @param username of a user whom wants to sign into the webiste with an
     * existing account.
     *
     * @param password of the user whom wants to sign into the website with an
     * existing account.
     *
     * @return boolean true if a session object was JUST created, false
     * otherwise
     */
    public Boolean tryLoggingIn(String username, String password) {
        if (username == null || password == null) {
            return false;
        }

        // Now call the Database function to see if the user exists
        Database d = Database.getDatabase();
        User u = null;
        try {
            u = d.getUserByUsernameAndPassword(username, password);
        } catch (SQLException ex) {
            Logger.getLogger(LoginPage.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (u == null || u.id == -1) {
            return false;
        }

        // If u isn't null and the id isn't -1, then
        // we want to create a session with the User object in it
        Session s = new Session(request);
        s.startSession(u);
        userID = u.id;

        return true;
    }
}